package com.qf.commerce.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.commerce.common.dto.CouponDto;
import com.qf.commerce.common.vo.CouponVo;
import com.qf.commerce.entity.Coupon;
import com.qf.commerce.mapper.CouponMapper;
import com.qf.commerce.service.CouponService;
import com.qf.commerce.utils.CommonBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 出品人:lsj
 * 1992915043@qq
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;
    @Override
    public PageInfo<CouponVo> getCouponPage(CouponDto couponDto, Integer page, Integer size) {
        return CommonBeanUtils.copyPage(PageHelper.startPage(page,size).
                        doSelectPageInfo(()->couponMapper.selectCoupon(couponDto)),
                new PageInfo<CouponVo>(),CouponVo::new);
    }

    @Override
    public int deleteCouponByCouponId(List<Long> couponId) {

          return  couponMapper.deleteByCouponId(couponId);


    }

    /**
     * 先根据id查询到当前信息
     * 再去判断当前id是否存在,存在就修改,不存在就添加
     * @param couponDto
     * @return
     *
     */
    @Override
    public int couponNowSession(CouponDto couponDto) {
        int count=0;
        Coupon coupon = couponMapper.selectCouponByCouponId(couponDto.getCouponId());
        //判断是否存在相同的优惠卷,存在就修改,不存在就添加
        if (ObjectUtils.isEmpty(coupon)){
            //不存在则插入
            coupon = CommonBeanUtils.copyForBean(couponDto, Coupon::new);
            count = couponMapper.insertCoupon(coupon);
        }else {
            count = couponMapper.updateByCouponId(coupon);
        }
        if (count<=0){
            throw  new RuntimeException("新增场次失败");
        }
        return count;
    }
}
